package com.gluck.cases.core.block.impl;

import com.gluck.cases.common.utils.dal.dao.PermissionMapper;
import com.gluck.cases.core.block.PermissionBlock;
import com.gluck.cases.core.modal.assemble.PermissionAssemble;
import com.gluck.cases.core.modal.dto.PermissionListDTO;
import com.gluck.cases.core.modal.entity.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName PermissionBlockImpl
 * @Desc PermissionBlockImpl
 * @Author I am Gluck
 * @Date 2022/5/17 - 8:32 下午
 **/
@Service
public class PermissionBlockImpl implements PermissionBlock {

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public List<Permission> findPermissionByRoleName(String name) {
        List<Permission> permissions = permissionMapper.findPermissionByRoleName(name);
        return permissions;
    }

    @Override
    public List<Permission> queryPermissionListByPid(Long pid) {
        List<Permission> permissions = permissionMapper.queryPermissionListByPid(pid);
        if (permissions.size() == 0) {
            return Collections.emptyList();
        }
        return permissions;
    }

    @Override
    public List<PermissionListDTO> queryPermissionByList(Long pid) {
        List<Permission> permissions = this.queryPermissionListByPid(pid);
        List<PermissionListDTO> dtos = PermissionAssemble.PermissionConvertDtoList(permissions);
        dtos.stream().forEach(x -> {
            List<PermissionListDTO> children = recursionPermissionByPid(x);
            x.setChildList(children);
        });
        return dtos;
    }

    /**
     * 功能描述: 递归调用子集
     * @Params [dto]
     * @Return java.util.List<com.gluck.stock.oauth.core.modal.dto.PermissionListDTO>
     * @Author I`m Gluck
     * @Date 2022/5/21
     */
    private List<PermissionListDTO> recursionPermissionByPid(PermissionListDTO dto) {
        List<Permission> children = this.queryPermissionListByPid(Long.valueOf(dto.getId()));
        List<PermissionListDTO> childrenDTOs = PermissionAssemble.PermissionConvertDtoList(children);
        childrenDTOs.stream().map((child) -> {
            List<PermissionListDTO> dtos = recursionPermissionByPid(child);
            child.setChildList(dtos);
            return child;
        }).collect(Collectors.toList());
        return childrenDTOs;
    }
}
